﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kelper.Domain.Models;
using Kelper.Domain.Data.Abstract;

namespace Kelper.Domain.Data
{
    public class UserRepository : IUserRepository
    {
        private KelperDbContext db;
        private IRegistrationConfirmation confirmation;

        public UserRepository(KelperDbContext db, IRegistrationConfirmation confirmation)
        {
            this.db = db;
            this.confirmation = confirmation;
        }

        public bool Register(User user)
        {
            User alreadyExists = Users.FirstOrDefault(u => u.Username == user.Username || u.Email == user.Email);
            if (alreadyExists != null)
                return false;

            db.Users.Add(user);
            db.SaveChanges();

            confirmation.SendConfirmation(user);

            return true;
        }

        public void Unregister(string user)
        {
            User databaseUser = Users.FirstOrDefault(u => u.Username == user);

            if (databaseUser != null)
            {
                db.Users.Remove(databaseUser);
                db.SaveChanges();
            }
        }

        public IQueryable<User> Users
        {
            get { return db.Users; }
        }
    }
}
